package com.bw.books.utils;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName Address
 * @Description 描述
 * @Author GYW
 */
@Component
public class Address {

    private static final Logger logger = LoggerFactory.getLogger(Address.class);

    public String parse(String addresspath) {
        String result = null;
        String host = "https://kzaddress2.market.alicloudapi.com";
        String path = "/api/address/parse";
        String method = "POST";
        String appcode = "08526b7f85d84860bf720d7b3dc172fb";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("address", addresspath);

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                result = EntityUtils.toString(response.getEntity());
                logger.info("成功解析地址: {}", result);
            } else {
                logger.error("HTTP 请求失败，状态码: {}", statusCode);
                throw new RuntimeException("HTTP 请求失败，状态码: " + statusCode);
            }
        } catch (IOException e) {
            logger.error("请求地址解析 API 时发生 IO 异常: ", e);
            throw new RuntimeException("请求地址解析 API 时发生 IO 异常", e);
        } catch (Exception e) {
            logger.error("请求地址解析 API 时发生未知异常: ", e);
            throw new RuntimeException("请求地址解析 API 时发生未知异常", e);
        }
        return result;
    }
}
